
package session1.practises;

import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Scanner;

public class TimerTest {
	public static void main(String[] args) {
		LinkedList<GoldfishTimer> goldfishTimers;
		Scanner scanner=new Scanner(System.in);
		int length;	boolean exit;
		while (true){
			goldfishTimers = new LinkedList<>();
			System.out.println("请输入若干时间（秒），输入-1结束输入");
			while (true) {
				try {
					if (	(length=scanner.nextInt()	) < 0) break;
					goldfishTimers.add(new GoldfishTimer(
							length, goldfishTimers.size())
					);
				} catch (InputMismatchException inputMismatchException) {break;}
			}

			if(goldfishTimers.isEmpty())return;
			for (GoldfishTimer goldfishTimer : goldfishTimers)
				goldfishTimer.start();

			while (true) {
				exit = true;
				for (GoldfishTimer goldfishTimer : goldfishTimers)
					if (goldfishTimer.getTimeLeft() > 0)
					{	exit = false;	break;}
				if(exit)break;
			}
		}
	}
}
class GoldfishTimer extends Thread{
	int timeLeft;
	int timerID;
	public GoldfishTimer(){}
	public int getTimeLeft() {return timeLeft;}
	public GoldfishTimer(int timeLeft, int timerID) {
		this.timeLeft = timeLeft;
		this.timerID = timerID;
	}
	@Override
	public void run() {
		while(--timeLeft>0){
			System.out.println("第"+(timerID+1)
					+"\t个计时器:剩余"+timeLeft+"\t秒");
			try {	Thread.sleep(1000);}
			catch 	(Exception e)
			{System.out.println(e.getMessage());}
		}
		System.out.println("第"+(timerID+1)+"\t个计时器结束");
	}
}
